<template>
  <div class="">
    <h1>{{id ? '编辑' : '新建'}}文章</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" placeholder="请选择" clearable multiple>
          <el-option
            v-for="item in categoriesOptions"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <vue-editor 
          @image-added="handleImageAdded"
          useCustomImageHandler
          v-model="model.content"></vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">{{id ? '保存' : '新建'}}</el-button>
      </el-form-item>
    </el-form>
  </div>
  
</template>

<script>
import { putArticleCreate, getArticleEditDetail, putArticleEdit } from '@/api/article'
import { getCategoryList } from '@/api/category'
import { uploadImage } from '@/api/tools'
import { VueEditor } from "vue2-editor";
export default {
  name: "ArticleEdit",
  components: {
    VueEditor
  },
  props: {
    id: {
      type: String
    }
  },
  data() {
    return {
      model: {},
      categoriesOptions: []
    };
  },
  created() {
    this.getParents()
    this.id && this.getArticleEditDetail()
  },
  methods: {
    // 富文本图片上传
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      let res = await uploadImage(formData)
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
    },
    async save() {
      let data = this.model
      if (this.id) {
        await putArticleEdit(this.id,data) //编辑数据
      } else {
        await putArticleCreate(data) //创建数据
      }
      this.$router.push('/articles/list')
      this.$message({
        type: 'success',
        message: this.id ? '编辑成功' : '创建成功'
      })
    },
    // 获取列表详情
    async getArticleEditDetail() {
      let res = await getArticleEditDetail(this.id)
      this.model = res.data
    },
    // 获取分类列表
    async getParents() {
      let params = {
        type: 'news'
      }
      let res = await getCategoryList(params)
      this.categoriesOptions = res.data.data
    }
  }
};
</script>

<style lang="less" scoped></style>
